package video;

import java.io.File;

import org.gstreamer.Gst;
import org.gstreamer.elements.PlayBin;
import org.gstreamer.Bus.EOS;

/**
 * Class that load and play a video.
 * 
 * @version 0.3 December 01, 2009.
 * @author Heitor Meira de Melo.
 */
public class MediaPlayer {
	private final String NO_LOADED_VIDEO = "No video file loaded.";
	private PlayBin playbin;
	private EOS endOfVideo;
	private RunVideo runVideo;

	/**
	 * A player constructor
	 * 
	 * @param endOfVideo
	 *            The action at the end of the stream in playbin.
	 */
	public MediaPlayer(EOS endOfVideo) {
		this.endOfVideo = endOfVideo;

	}

	/**
	 * Creates a video, in a new thread, ready to play.
	 * 
	 * @return The video.
	 * @throws Exception
	 *             If the file is invalid.
	 */
	public RunVideo createPlayer(File video) throws Exception {
		if (!video.isFile()) {
			throw new Exception("Invalid File");
		}

		Gst.init();

		playbin = new PlayBin("VideoPlayer");
		playbin.getBus().connect(endOfVideo);

		runVideo = new RunVideo(playbin);
		setInputPlaybinFile(video);

		return runVideo;

	}

	/**
	 * Update the current video in playbin to the parameter.
	 * 
	 * @param video
	 *            The video to update.
	 */
	public void setInputPlaybinFile(File video) {
		if (playbin.isPlaying()) {
			playbin.stop();
			playbin.setInputFile(video);
			playbin.play();

		} else {
			playbin.setInputFile(video);
		}
	}

	/**
	 * Stop the playbin and sets the components to null.
	 */
	public void kill() {
		playbin.stop();
		playbin = null;
	}

	/**
	 * Play the playbin.
	 */
	public void play() {
		playbin.play();
	}

	/**
	 * Stop the playbin.
	 */
	public void stop() {
		playbin.stop();
	}

	/**
	 * Pause the playbin.
	 */
	public void pause() {
		playbin.pause();
	}

	/**
	 * Test if the video is playing
	 * 
	 * @return true if the playbin if playing, false otherwise.
	 */
	public boolean isPlaying() {
		return playbin.isPlaying();
	}

	/**
	 * Returns the current video, in a new thread.
	 * 
	 * @return the current video.
	 */
	protected RunVideo getRunVideo() {
		return runVideo;
	}

}
